package bavaria.hightech.banking.gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.JTextField;

import bavaria.hightech.banking.exceptions.AccountNotAvailableException;
import bavaria.hightech.banking.exceptions.BankDoesNotExistException;
import bavaria.hightech.banking.exceptions.FixedDepositException;
import bavaria.hightech.banking.exceptions.NotEnoughMoneyException;
import bavaria.hightech.banking.money.Currency;

/**
 * ActionListener for the transfer button under "Transfer" Transfers, if
 * possible, money to an receiver account
 * 
 * @author Dietmar
 */
public class ListenerTransferButton implements ActionListener {

	private JTextField accNrToTextField;
	private JTextField amountTextField;
	private GlobalVarsContainer cont;

	public ListenerTransferButton(JTextField accNrToTextField,
			JTextField amountTextField, GlobalVarsContainer cont) {
		this.accNrToTextField = accNrToTextField;
		this.amountTextField = amountTextField;
		this.cont = cont;
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		PanelTransfer transfer = new PanelTransfer(cont);
		JPanel transferJPanel = transfer.getJPanel();

		if (cont.getSelAccNr() == -1) {
			cont.setStatusLabel("specify a valid sender acc first!");
			return;
		}

		try {
			if (cont.getBank().isValidAccNr(cont.getSelAccNr())) {
				cont.getBank().transferMoney(cont.getBank().bankName,
						Currency.currencyEnum.EURO, Currency.currencyEnum.EURO,
						cont.getSelAccNr(),
						Integer.parseInt(accNrToTextField.getText()),
						Integer.parseInt(amountTextField.getText()), "GUITest");
				cont.setStatusLabel("Money transferred successfully");
			} else {
				cont.setStatusLabel("transfer failed!");
			}

		} catch (FixedDepositException e) {
			cont.setStatusLabel("transfer failed!");
		} catch (BankDoesNotExistException e) {
			cont.setStatusLabel("transfer failed!");
		} catch (AccountNotAvailableException e) {
			cont.setStatusLabel("transfer failed!");
		} catch (NotEnoughMoneyException e) {
			cont.setStatusLabel("transfer failed!");
		} catch (IllegalStateException e) {
			cont.setStatusLabel("transfer failed!");
		} catch (NullPointerException e) {
			cont.setStatusLabel("transfer failed!");
		} catch (NumberFormatException e) {
			cont.setStatusLabel("transfer failed!");
		}

		cont.getContentWrapper().removeAll();
		cont.getContentWrapper().add(transferJPanel, BorderLayout.CENTER);
		cont.getContentWrapper().validate();
	}

}
